<template>
  <router-view></router-view>
</template>

<script setup>
import { ref, provide,watch } from 'vue'

// 从localStorage加载数据的函数
const loadFromLocalStorage = (key, defaultValue = []) => {
  try {
    const stored = localStorage.getItem(key)
    return stored ? JSON.parse(stored) : defaultValue
  } catch (error) {
    console.error(`Error loading ${key} from localStorage:`, error)
    return defaultValue
  }
}

// 保存数据到localStorage的函数
const saveToLocalStorage = (key, data) => {
  try {
    localStorage.setItem(key, JSON.stringify(data))
  } catch (error) {
    console.error(`Error saving ${key} to localStorage:`, error)
  }
}

// 创建响应式数据存储保存的城市列表
const savedCities = ref(loadFromLocalStorage('savedCities'))
// 创建响应式数据存储已访问的城市列表
const visitedCities = ref(loadFromLocalStorage('visitedCities'))

// 监听savedCities变化，自动保存到localStorage
watch(savedCities, (newVal) => {
  saveToLocalStorage('savedCities', newVal)
}, { deep: true })

// 监听visitedCities变化，自动保存到localStorage
watch(visitedCities, (newVal) => {
  saveToLocalStorage('visitedCities', newVal)
}, { deep: true })


// 提供方法给子组件使用
const addCity = (cityInfo) => {
  // 检查是否已存在相同城市
  const exists = savedCities.value.some((city) => city.name === cityInfo.name)
  if (!exists) {
    savedCities.value.push(cityInfo)
  }
}

// 提供数据和方法给所有子组件
provide('savedCities', savedCities)
provide('visitedCities', visitedCities)
provide('addCity', addCity)
</script>

<style>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
/* 添加全局字体样式 */
body {
  font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
    Segoe UI, Roboto, Helvetica Neue, Arial, Noto Sans, sans-serif,
    'Apple Color Emoji', 'Segoe UI Emoji', Segoe UI Symbol, 'Noto Color Emoji';
}
</style>
